# db.py
import pymysql
from pymysql.cursors import DictCursor

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'social',
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}


def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


# 初始化数据库
def init_db():
    try:
        conn = get_db_connection()
        with conn.cursor() as cursor:
            # 创建用户表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    username VARCHAR(80) UNIQUE NOT NULL,
                    password_hash VARCHAR(120) NOT NULL
                )
            ''')

            # 创建帖子表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS posts (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    title VARCHAR(100) NOT NULL,
                    content TEXT NOT NULL,
                    user_id INT NOT NULL,
                    FOREIGN KEY (user_id) REFERENCES users(id)
                )
            ''')
        conn.commit()
    except Exception as e:
        print(f"数据库初始化错误: {e}")
    finally:
        if conn:
            conn.close()


# 其他CRUD函数...